package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {


    @Resource
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {
        System.out.println("参数：" + params);
        SearchRequest request = new SearchRequest("hotel");
        booleanQuery(params, request);
        Integer page = params.getPage();
        Integer size = params.getSize();
        request.source().from((page - 1) * size).size(size);
        SearchResponse search = null;

        try {
            search = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        assert search != null;
        PageResult pageResult = handleResponse(search);
        System.out.println("输出：" + pageResult);
        return pageResult;
    }

    @Override
    public Map<String, List<String>> filters(RequestParams params) {

        SearchRequest request = new SearchRequest("hotel");
        booleanQuery(params, request);
        request.source().size(0);
        request.source().aggregation(AggregationBuilders.terms("brandAgg").size(100).field("brand"));
        request.source().aggregation(AggregationBuilders.terms("cityAgg").size(100).field("city"));
        request.source().aggregation(AggregationBuilders.terms("starAgg").size(100).field("starName"));
        Map<String, List<String>> map = null;
        try {
            map = new HashMap<>();
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Aggregations aggregations = response.getAggregations();
            List<String> brandAggKeys = getList(aggregations, "brandAgg");
            List<String> cityAggKeys = getList(aggregations, "cityAgg");
            List<String> starAggKeys = getList(aggregations, "starAgg");
            map.put("品牌", brandAggKeys);
            map.put("城市", cityAggKeys);
            map.put("星级", starAggKeys);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public List<String> getSuggestion(String prefix) {
        SearchRequest request = new SearchRequest("hotel");

        request.source().suggest(new SuggestBuilder().addSuggestion("sss", SuggestBuilders.completionSuggestion("suggestion").size(10).prefix(prefix).skipDuplicates(true)));

        SearchResponse search = null;
        try {
            search = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        assert search != null;
        Suggest suggest = search.getSuggest();

        CompletionSuggestion suggestion = suggest.getSuggestion("sss");
        List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
        List<String> list=new ArrayList<>();


        for (CompletionSuggestion.Entry.Option option : options) {
            String key = option.getText().toString();
            list.add(key);
        }


        return list;
    }

    private List<String> getList(Aggregations aggregations, String aggName) {
        Terms terms = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();

        List<String> keys = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String key = (String) bucket.getKey();
            keys.add(key);
        }
        return keys;
    }

    private void booleanQuery(RequestParams params, SearchRequest request) {
        String key = params.getKey();
        Integer page = params.getPage();
        Integer size = params.getSize();
        String brand = params.getBrand();
        String city = params.getCity();
        String location = params.getLocation();
        String starName = params.getStarName();
        String sortBy = params.getSortBy();
        Integer maxPrice = params.getMaxPrice();
        Integer minPrice = params.getMinPrice();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        if (key == null || "".equals(key)) {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        }

        if (city != null && !"".equals(city)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("city", city));
        }
        if (starName != null && !"".equals(starName)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName", starName));
        }
        if (location != null && !"".equals(location)) {
            request.source().sort(SortBuilders.geoDistanceSort("location", new GeoPoint(location)));
        }
        if (brand != null && !"".equals(brand)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", brand));
        }
        if (sortBy != null && !"".equals(sortBy) && !"default".equals(sortBy)) {
            request.source().query(boolQueryBuilder).sort(sortBy);
        }
        if (maxPrice != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(maxPrice));
        }
        if (minPrice != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(minPrice));
        }

        FunctionScoreQueryBuilder scoreQuery = QueryBuilders.functionScoreQuery(boolQueryBuilder, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{new FunctionScoreQueryBuilder.FilterFunctionBuilder(


                QueryBuilders.termQuery("isAD", true), ScoreFunctionBuilders.weightFactorFunction(10))});
        request.source().query(boolQueryBuilder);
    }

    private PageResult handleResponse(SearchResponse search) {

        SearchHits hits = search.getHits();
        SearchHit[] hitsHits = hits.getHits();
        long total = hits.getTotalHits().value;

        PageResult pageResult = new PageResult();

        List<HotelDoc> list = new ArrayList<>();

        for (SearchHit hitsHit : hitsHits) {
            String HotelDocJson = hitsHit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(HotelDocJson, HotelDoc.class);
            Object[] sortValues = hitsHit.getSortValues();
            if (sortValues.length > 0) {
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }

            list.add(hotelDoc);
        }

        pageResult.setTotal(total);
        pageResult.setHotels(list);


        return pageResult;
    }


}
